package com.lynx.service.impl;

import com.lynx.util.EncryptUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lynx.mapper.cb.AccountMapper;
import com.lynx.mapper.cb.model.UserPO;
import com.lynx.controller.model.User;
import com.lynx.service.AccountService;
import com.lynx.service.exception.UserException;

/**
 * @author chris.liu
 * @version 4/17/14 11:11 PM
 */
@Service("accountService")
public class AccountServiceImpl implements AccountService {

	@Autowired
	private AccountMapper accountMapper;

	@Override
	public User getUserInfo(int id) throws UserException {
		UserPO po = accountMapper.getUserById(id);
        if (po != null) {
            return po2vo(po);
        }
		return null;
	}

	@Override
	public User login(String id, String pwd) throws UserException {
		UserPO po = accountMapper.getUserByNameAndPwd(id, pwd);
		if (po != null) {
			if (isValidUser(pwd, po)) {
				return po2vo(po);
			} else {
				return null;
			}
		}
		po = accountMapper.getUserByEmailAndPwd(id, pwd);
		if (po != null) {
			if (isValidUser(pwd, po)) {
				return po2vo(po);
			} else {
				return null;
			}
		}
		throw new UserException("login error");
	}

	@Override
	public boolean logout() throws UserException {
		return false;
	}

	@Override
	public User updateUserInfo(User user) throws UserException {

		return null;
	}

	private User po2vo(UserPO po) {
		User vo = new User();
		vo.setId(po.getId());
		vo.setName(po.getName());
		vo.setEmail(po.getEmail());
		vo.setGender(po.getGender());
		vo.setCreateTime(po.getCreateTime());
		vo.setToken(EncryptUtil.generateToken(po.getId(), 1));
		return vo;
	}

	private UserPO vo2po(User vo) {
		UserPO po = new UserPO();
		if (StringUtils.isNotBlank(vo.getName())) {
			po.setName(vo.getName());
		}
		po.setGender(vo.getGender());
		if (StringUtils.isNotBlank(vo.getEmail())) {
			po.setEmail(vo.getEmail());
		}
		if (vo.getCreateTime() != null) {
			po.setCreateTime(vo.getCreateTime());
		}
		return po;
	}

	/**
	 * 根据用户信息判定该用户是否为正常成功登陆用户
	 * 
	 * @param pwd
	 * @param po
	 * @return
	 */
	private boolean isValidUser(String pwd, UserPO po) {
		if (StringUtils.isNotBlank(pwd) && pwd.equals(po.getPwd())) {
			return true;
		}
		return false;
	}
}
